package com.higgins.eventtracking.client.health.record.entry;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.higgins.eventtracking.client.EventTrackingService;
import com.higgins.eventtracking.client.EventTrackingServiceAsync;
import com.higgins.eventtracking.client.dto.BodyStatsDTO;

public class Weight extends VerticalPanel	{
	private static final String SERVER_ERROR = "An error occurred while "
		+ "attempting to contact the server. Please check your network "
		+ "connection and try again.";

	private final EventTrackingServiceAsync greetingService = GWT
			.create(EventTrackingService.class);
	private boolean firstRun = true;
	
	public Weight()	{	}
	
	public void update()	{
		if (firstRun)	
			initialise();
	}
	
	public void initialise()	{
		final Button sendButton = new Button("Add");
		final TextBox nameField = new TextBox();
		nameField.setText("GWT User1");

		final TextBox weightTextBox = new TextBox();
		weightTextBox.setText("0.0");
		final TextBox fatPercentageTextBox = new TextBox();
		fatPercentageTextBox.setText("0.0");
		final TextBox waterPercentageTextBox = new TextBox();
		waterPercentageTextBox.setText("0.0");
		final TextBox musclePercentageTextBox = new TextBox();
		musclePercentageTextBox.setText("0.0");
		final TextBox fatCalipersTextBox = new TextBox();
		fatCalipersTextBox.setText("0");
		
		final Label errorLabel = new Label();

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		add(new Label("Weight (KG)"));
		add(weightTextBox);
		add(new Label("Body Fat (%)"));
		add(fatPercentageTextBox);
		add(new Label("Water (%)"));
		add(waterPercentageTextBox);
		add(new Label("Muscle (%)"));
		add(musclePercentageTextBox);
		add(new Label("Fat Calipers"));
		add(fatCalipersTextBox);
		add(sendButton);
	
			// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendTrackingEventToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendTrackingEventToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendTrackingEventToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				
				BodyStatsDTO bodyStatsDTO = new BodyStatsDTO();
				bodyStatsDTO.setTimestamp(new Date());
				bodyStatsDTO.setWeight(new Double(weightTextBox.getText()));
				bodyStatsDTO.setFatPercentage(new Double(fatPercentageTextBox.getText()));
				bodyStatsDTO.setWaterPercentage(new Double(waterPercentageTextBox.getText()));
				bodyStatsDTO.setMusclePercentage(new Double(musclePercentageTextBox.getText()));
				bodyStatsDTO.setFatCalipers(new Integer(fatCalipersTextBox.getText()));
				
				
				sendButton.setEnabled(false);
				greetingService.insertBodyEvent(bodyStatsDTO,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox.setText("Remote Procedure Call - Failure");
								serverResponseLabel.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								dialogBox.setPopupPosition(0, 0);
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								dialogBox.center();
								dialogBox.setPopupPosition(0, 0);
								closeButton.setFocus(true);
							}
						});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
	}		
}
